package littlewhisker.managers {
	import littlewhisker.globals.constants.errortypes.LWErrorTypes;
	import flash.net.URLRequest;
	import flash.events.SecurityErrorEvent;
	import flash.events.IOErrorEvent;

	import littlewhisker.globals.constants.eventtypes.LWEventTypes;

	import flash.events.Event;
	import flash.events.EventDispatcher;
	import littlewhisker.managers.ConfigManager;
	import flash.net.URLLoader;
	/**
	 * @author Philip
	 */
	
		public class ConfigManager extends EventDispatcher {
		
		public static var loaded:Boolean=false;
		//
		 private static var instance:ConfigManager;
      private static var allowInstantiation:Boolean;
      

		//
		private var configXML:XML;
		private var loader:URLLoader;
		public function ConfigManager()
		{
			if (!allowInstantiation) {
            	throw new Error(LWErrorTypes.SINGLETON_INSTANSIATION);
			}
		}
	
		
      public static function getInstance():ConfigManager {
         if (instance == null) {
            allowInstantiation = true;
            instance = new ConfigManager();
            allowInstantiation = false;
          }
         return instance;
       }
		
		public function load(configFile:String):void{
			loader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, onXmlComplete);
			loader.addEventListener(IOErrorEvent.IO_ERROR, onXmlFail);
			loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onXmlFail);
			loader.load(new URLRequest(configFile));
		}
		
		public function getSettings():XMLList{
			return configXML.descendants("setting");
		}
		
		public function getAssets():XMLList{
			return configXML.descendants("asset");
		}
		
		public function getXML():XML{
			return configXML;
		}
		
		private function onXmlComplete(e:Event):void{
			
			configXML = new XML(e.target.data);
			loaded=true;
			dispatchEvent(new Event(LWEventTypes.ON_COMPLETE));
			disposeLoader();
		}
		private function onXmlFail(e:Event):void{
			
			dispatchEvent(new Event(LWEventTypes.ON_FAIL));
			disposeLoader();
		}
		private function disposeLoader():void{
			loader.removeEventListener(Event.COMPLETE, onXmlComplete);
			loader.removeEventListener(IOErrorEvent.NETWORK_ERROR, onXmlFail);
			loader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onXmlFail);
			loader=null;
		}
		
	}
}
